package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        log.info("执行登录操作, employee = {}", employee);

        //1、将页面提交的密码password进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        //2、根据页面提交的用户名username查询数据库
//        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", employee.getUsername());
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(queryWrapper);
        //3、如果没有查询到则返回登录失败结果
        if (one == null){
            log.info("用户名或密码错误!");
            return R.error("用户名或密码错误!");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!password.equals(one.getPassword())){
            log.info("用户名或密码错误!");
            return R.error("用户名或密码错误!");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(one.getStatus() == 0){
            log.info("该账号被禁用, 请联系管理员!");
            return R.error("该账号被禁用, 请联系管理员!");
        }

        //6、登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee", one.getId());
        return R.success(one);
    }


    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        log.info("执行退出操作");
        request.getSession().invalidate();
        return R.success();
    }


    @PostMapping
    public R save(@RequestBody Employee employee){
        //组装数据
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employeeService.save(employee);

        return R.success();
    }


    /**
     * 分页查询
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(required = false, defaultValue = "1") int page ,
                                  @RequestParam(required = false, defaultValue = "10") int pageSize , String name){
        //1. 封装分页参数
        Page<Employee> pageInfo = new Page<>(page,pageSize);

        //2. 组装查询条件, 排序条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName, name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //3. 执行分页查询
        employeeService.page(pageInfo, queryWrapper);

        //4. 返回结果
        return R.success(pageInfo);
    }


    /**
     * 修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R update(HttpServletRequest request, @RequestBody Employee employee){
        log.info("执行修改员工操作, employee = {}", employee.toString());
        //1. 补全属性
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);

        //System.out.println("当前线程ID: " + Thread.currentThread().getId());

        //2. 执行更新
        employeeService.updateById(employee);
        return R.success();
    }


    /**
     * 根据ID查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据ID查询员工信息, id={}", id);
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("所查询的员工信息不存在!");
    }

}
